package com.xmmj.baselibrary.network

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import com.xmmj.baselibrary.base.application.BaseApplication
import okhttp3.Interceptor
import retrofit2.Converter
import java.io.File
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLSocketFactory

/**
 * 网络请求工具类
 */
object RetrofitUtil {
    //服务端地址
    private var baseUrl: String? = null

    //连接超时
    private var connectTimeout: Long = (10 * 1000).toLong()

    //读取超时
    private var readTimeout: Long = (10 * 1000).toLong()

    //写入超时
    private var writeTimeout: Long = (10 * 1000).toLong()

    //是否尝试重连
    private var retryOnConnection: Boolean = true

    //证书
    private var certificate: File? = null

    //拦截器
    private var interceptors: Array<Interceptor>? = null

    //转换器
    private var converter: Converter.Factory? = null

    /**
     * 获取API接口
     *
     * @param tClass API 类
     */
    fun <T> getService(tClass: Class<T>?): T {
        //okhttp配置
        val okhttpBuilder = OkHttpClient.Builder()
        okhttpBuilder.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
        okhttpBuilder.readTimeout(readTimeout, TimeUnit.MILLISECONDS)
        okhttpBuilder.writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)
        okhttpBuilder.retryOnConnectionFailure(retryOnConnection)

        //添加拦截器
        interceptors?.forEach {
            okhttpBuilder.addInterceptor(it)
        }

        //日志输出
        if (BaseApplication.isDebug) {
            val loggingInterceptor = HttpLoggingInterceptor()
            loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
            okhttpBuilder.addInterceptor(loggingInterceptor)
        }

        //https证书认证
        //（如果服务端用的是自己生成的证书，那么Android就需要使用下面的代码对证书进行校验，
        //如果服务端使用的是机构颁发的证书就不需要下面的代码，系统会默认信任这类证书）
        certificate?.let {
            val httpsUtil: HttpsUtil? = HttpsUtil.instance
            val sslSocketFactory: SSLSocketFactory? = httpsUtil!!.setCertificates(certificate!!)
            okhttpBuilder.hostnameVerifier { hostname, session ->
                hostname.equals(session.peerHost)
            }.sslSocketFactory(sslSocketFactory, httpsUtil.x509TrustManager)
        }

        //Retrofit配置
        val retrofitBuilder = Retrofit.Builder()
        //设置服务器地址
        retrofitBuilder.baseUrl(baseUrl)
        //设置客户端
        retrofitBuilder.client(okhttpBuilder.build())
        //添加转换器
        converter.let { retrofitBuilder.addConverterFactory(converter) }
        //添加适配器
        retrofitBuilder.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        return retrofitBuilder.build().create(tClass)
    }


    fun baseUrl(host: String): RetrofitUtil {
        RetrofitUtil.baseUrl = host
        return this
    }

    fun connectTimeout(connectTimeout: Long): RetrofitUtil {
        RetrofitUtil.connectTimeout = connectTimeout
        return this
    }

    fun readTimeout(readTimeout: Long): RetrofitUtil {
        RetrofitUtil.readTimeout = readTimeout
        return this
    }

    fun writeTimeout(writeTimeout: Long): RetrofitUtil {
        RetrofitUtil.writeTimeout = writeTimeout
        return this
    }

    fun retryOnConnection(retryOnConnection: Boolean): RetrofitUtil {
        RetrofitUtil.retryOnConnection = retryOnConnection
        return this
    }

    fun interceptors(interceptors: Array<Interceptor>): RetrofitUtil {
        RetrofitUtil.interceptors = interceptors
        return this
    }

    fun certificate(file: File): RetrofitUtil {
        certificate = file
        return this
    }

    fun converter(converter: Converter.Factory): RetrofitUtil {
        RetrofitUtil.converter = converter
        return this
    }

}